package sicnu.cs.ich.activity.service.impl;

import com.mongodb.client.result.UpdateResult;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import sicnu.cs.ich.activity.domain.ActivityLike;
import sicnu.cs.ich.activity.domain.CommentLike;
import sicnu.cs.ich.activity.service.ICommentLikeService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * @author 黎琦
 * @date 2021/12/7 20:06
 **/
@Service
@RequiredArgsConstructor
public class CommentLikeServiceImpl implements ICommentLikeService {
    private final MongoTemplate mongoTemplate;

    @Override
    public void insert(CommentLike commentLike) {
        mongoTemplate.save(commentLike);
    }

    @Override
    public Long updateByCid(Integer cid, Integer uid) {
        //添加用户id，并更新点赞数
        Query query = new Query(Criteria.where("cid").is(cid));
        CommentLike commentLike = mongoTemplate.findOne(query, CommentLike.class);
        if(commentLike==null){
            throw new NoSuchElementException("该活动不存在");
        }
        Update update = new Update();
        update.addToSet("uidList", uid);
        update.inc("likeNum", 1);
        long modifiedCount = mongoTemplate.updateFirst(query, update, ActivityLike.class).getModifiedCount();
        if (modifiedCount==0){
            throw new RuntimeException("重复点赞错误");
        }

        return commentLike.getLikeNum()+1;
    }

    @Override
    public Long getLikeNum(Integer cid) {
        Query query = new Query(Criteria.where("cid").is(cid));
        CommentLike commentLike = mongoTemplate.findOne(query, CommentLike.class);
        if(commentLike==null){
            throw new NoSuchElementException("该活动不存在");
        }
        return commentLike.getLikeNum();
    }

    @Override
    public Map<Integer,CommentLike> getCommentLikesByAid(Integer aid) {
        Query query = new Query(Criteria.where("aid").is(aid));
        List<CommentLike> commentLikes = mongoTemplate.find(query, CommentLike.class);
        HashMap<Integer, CommentLike> map = new HashMap<>(commentLikes.size());
        for (CommentLike commentLike : commentLikes) {
            map.put(commentLike.getCid(), commentLike);
        }
        return map;
    }
}
